/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logiclander.adhocracy.jira.cli;

import com.atlassian.jira.rest.client.JiraRestClient;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Predicates.notNull;
import com.logiclander.adhocracy.cli.CommandLineReactorFactory;
import com.logiclander.adhocracy.jira.config.JerseyJiraRestClientFactorySSLv3;
import java.io.Console;
import java.net.URI;
import java.net.URISyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 *
 * @author tim
 */
public abstract class JiraCommandLineReactorFactory implements CommandLineReactorFactory {

    final JerseyJiraRestClientFactorySSLv3 factory = new JerseyJiraRestClientFactorySSLv3();
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final URI jiraApiUri;
    private final String jiraApiUsr;
    private final String jiraApiPsw;

    public JiraCommandLineReactorFactory(ApplicationContext context) {
        URI uri = null;
        String usr = null;
        String psw = null;
        checkArgument(notNull().apply(context), "springContext cannot be null");
        try {
            uri = new URI((String) context.getBean("jiraApiUri"));
        } catch (URISyntaxException ex) {
            logger.error("error configuring jira rest api uri", ex);
        }
        if ((Boolean) context.getBean("jiraApiPromptForAuthN")) {
            Console c = System.console();
            if (c != null) {
                usr = c.readLine("[%s]", "username:");
                psw = new String(c.readPassword("[%s]", "password:"));

            }
        } else {
            usr = (String) context.getBean("jiraApiUsername");
            psw = (String) context.getBean("jiraApiPassword");
        }
        jiraApiUri = uri;
        jiraApiUsr = usr;
        jiraApiPsw = psw;
    }

    public JiraRestClient getJiraRestClient() {
        return factory.createWithBasicHttpAuthentication(jiraApiUri, jiraApiUsr, jiraApiPsw);
    }
    
    public String getJiraApiUsr () {
        return jiraApiUsr;
    }
}
